import 'dart:async';
import 'package:boss/channel/baiduSpeech/baidu_speech.dart';
import 'package:boss/channel/baiduSpeech/baidu_speech_constant.dart';
import 'package:boss/channel/baiduSpeech/baidu_speech_error.dart';
import 'package:boss/models/commodity.dart';
import 'package:boss/provider/commodity_provider.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';
import 'package:provider/provider.dart';
import 'package:svgaplayer_flutter/svgaplayer_flutter.dart';

Future showSpeechRecognitionCommodityModal(BuildContext context) {
  return showModalBottomSheet(
    context: context,
    builder: (context) => _SpeechRecognitionCommodityModal(),
  );
}

class _SpeechRecognitionCommodityModal extends StatefulWidget {
  @override
  _SpeechRecognitionCommodityModalState createState() => _SpeechRecognitionCommodityModalState();
}

class _SpeechRecognitionCommodityModalState extends State<_SpeechRecognitionCommodityModal> with SingleTickerProviderStateMixin {
  bool isSpeeking = false;

  StreamSubscription<String> speechRecognitionStreamSubscription;
  StreamSubscription<String> statusStreamSubscription;
  StreamSubscription<String> flushStreamSubscription;
  StreamSubscription<BaiduSpeechErrorResponse> errorStreamSubscription;

  String status = BaiduSpeechConstant.ASR_PREPARING;

  String word = '';

  String get title {
    if (isSpeeking) {
      switch (status) {
        case BaiduSpeechConstant.ASR_PREPARING:
          return '引擎准备中...';
        case BaiduSpeechConstant.ASR_READY:
          return '请长按说出菜品和价格';
        default:
          return word;
      }
    } else {
      if (status != BaiduSpeechConstant.ASR_PREPARING) {
        return word;
      }

      return '请长按说出菜品和价格';
    }
  }

  toggleSpeaking(bool flag) {
    setState(() {
      isSpeeking = flag;

      if (isSpeeking) {
        word = '请说出菜品和价格';
      }
    });
  }

  @override
  void initState() {
    super.initState();

    speechRecognitionStreamSubscription = BaiduSpeech.instance.speechRecognitionStream.listen(speechRecognitionHandle);

    statusStreamSubscription = BaiduSpeech.instance.statusEventStream.listen(statusHandle);

    flushStreamSubscription = BaiduSpeech.instance.flushDataStream.listen(flushHandle);

    errorStreamSubscription = BaiduSpeech.instance.errEventStream.listen(errorHandle);
  }

  @override
  void dispose() {
    speechRecognitionStreamSubscription.cancel();
    speechRecognitionStreamSubscription = null;

    statusStreamSubscription.cancel();
    statusStreamSubscription = null;

    flushStreamSubscription.cancel();
    flushStreamSubscription = null;

    errorStreamSubscription.cancel();
    errorStreamSubscription = null;

    super.dispose();
  }

  speechRecognitionHandle(String word) async {
    try {
      var price = ChineseMontyUtil.transferText2Price(word);
      var name = ChineseMontyUtil.transferText2Name(word);

      setState(() {
        isSpeeking = false;

        this.word = word;
      });

      var commodityProvider = Provider.of<CommodityProvider>(
        context,
        listen: false,
      );

      if (commodityProvider.storeMenus.length == 0) {
        toast('暂无菜品分类,请先添加菜品分类再进行该操作');
        return;
      }
      var menu = commodityProvider.storeMenus[0];

      var result = await commodityProvider.saveCommodity(Commodity.fromJson({
        'title': name,
        'price': price,
        'menuId': menu.menuId,
        'unit': '份',
      }));

      if (result) {
        Navigator.pop(context);
      }
    } catch (e) {
      print(e);
      setState(() {
        this.word = '识别失败，请重试';
      });
    }
  }

  statusHandle(String status) {
    setState(() {
      this.status = status;
    });
  }

  flushHandle(String word) {
    setState(() {
      this.word = word;
    });
  }

  errorHandle(BaiduSpeechErrorResponse error) {
    print('errorHandle:errCode(${error.errCode}),errMessage(${error.errMessage})');
    setState(() {
      isSpeeking = false;
      word = '识别失败，请重试';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.only(top: 80.w),
      height: 600.w,
      child: Column(
        children: <Widget>[
          Text(
            '$title',
            style: TextStyleConstant().normal_1_50,
          ),
          Opacity(
            opacity: isSpeeking || status != BaiduSpeechConstant.ASR_PREPARING ? 0.0 : 1.0,
            child: Container(
              margin: EdgeInsets.only(
                top: 34.w,
              ),
              child: Text(
                '例如：麻辣小龙虾 50元',
                style: TextStyleConstant().normal_1_28,
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 75.w),
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTapDown: (_) {
                toggleSpeaking(true);

                BaiduSpeech.instance.start();
              },
              onTapUp: (_) {
                toggleSpeaking(false);

                BaiduSpeech.instance.end();
              },
              child: SizedBox(
                  width: 300.w,
                  height: 300.w,
                  child: Stack(
                    children: <Widget>[
                      if (isSpeeking)
                        SVGASimpleImage(
                          assetsName: 'assets/image/speech_recognition.svga',
                        ),
                      BaseImage(
                        'assets/image/speech_recognition.png',
                      ),
                    ],
                  )),
            ),
          )
        ],
      ),
    );
  }
}
